package me.nereo.multi_image_selector;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.ali.music.multi_image_selector.R;
import com.ali.music.multiimageselector.MultiImageSelectorUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.adapter.ImageGridAdapter;
import me.nereo.multi_image_selector.bean.Folder;
import me.nereo.multi_image_selector.bean.Image;
import me.nereo.multi_image_selector.utils.FileUtils;
import me.nereo.multi_image_selector.utils.TimeUtils;
/**
 * 图片选择Fragment
 * Created by Nereo on 2015/4/7.
 */
public class MultiImageSelectorFragment extends Fragment implements ImageGridAdapter.OnPhotoItemCheckedListener {
    private static final String TAG = "MultiImageSelector";

    /**
     * 单选
     */
    public static final int MODE_SINGLE = 0;
    /**
     * 多选
     */
    public static final int MODE_MULTI = 1;
    /**
     * 单选 且 切图
     */
    public static final int MODE_SINGLE_CROP = 2;

    // 不同loader定义
    private static final int LOADER_ALL = 0;
    private static final int LOADER_CATEGORY = 1;

    // 请求加载系统照相机
    private static final int REQUEST_CAMERA = 100;
    //单个图片选择
    private static final int REQUEST_CROP_SINGLE = 101;
    //单个图片选择，拍照
    private static final int REQUEST_CROP_CAMERA = 102;

    //当前的mode
    private int mCurMode;
    //最大选择图片数
    private int mMaxCount;
    //是否现实相机
    private boolean mIsShowCamera = false;
    // 结果数据
    private ArrayList<String> mResultList = new ArrayList<>();
    // 文件夹数据
    private ArrayList<Folder> mResultFolder = new ArrayList<>();
    private File mTmpFile;
    //拍照缓存文件

    // 图片Grid
    private GridView mGridView;
    // 时间线
    private TextView mTimeLineText;
    //提交
    private Button mSubmitButton;
    private Button mCategoryBtn;

    private ImageGridAdapter mImageAdapter;
    private SelectorPhotoFolder mSelectorPhotoFolder;
    private boolean mHasFolderGened = false;
    private int mGridWidth, mGridHeight;

    private void initToolbar(View view) {
        // 返回按钮o
        view.findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().setResult(Activity.RESULT_CANCELED);
                getActivity().finish();
            }
        });

        mSubmitButton = (Button) view.findViewById(R.id.commit);
        refrashSubmit();
        mSubmitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mResultList != null && mResultList.size() > 0) {
                    // 返回已选择的图片数据
                    Intent data = new Intent();
                    data.putStringArrayListExtra(MultiContent.EXTRA_RESULT, mResultList);
                    getActivity().setResult(Activity.RESULT_OK, data);
                    getActivity().finish();
                }
            }
        });
        mCategoryBtn = (Button) view.findViewById(R.id.category_btn);
        mCategoryBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectorPhotoFolder.isShowing()) {
                    mSelectorPhotoFolder.hide();
                } else {
                    mSelectorPhotoFolder.show(v);
                }
            }
        });
        mCategoryBtn.setText(R.string.multi_folder_all);
    }

    private void refrashSubmit() {
        if (mResultList == null || mResultList.size() <= 0) {
            mSubmitButton.setText(R.string.multi_next);
            mSubmitButton.setEnabled(false);
        } else {
            mSubmitButton.setText(getString(R.string.multi_next_num, mResultList.size(), mMaxCount));
            mSubmitButton.setEnabled(true);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.multi_fragment_image, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 选择图片数量
        mMaxCount = getArguments().getInt(PrivateContent.EXTRA_SELECT_COUNT);
        // 图片选择模式
        mCurMode = getArguments().getInt(PrivateContent.EXTRA_MODE);
        // 默认选择
        if (mCurMode == MODE_MULTI) {
            ArrayList<String> tmp = getArguments().getStringArrayList(PrivateContent.EXTRA_DEFAULT_SELECTED_LIST);
            if (tmp != null && tmp.size() > 0) {
                mResultList = tmp;
            }
        }
        // 是否显示照相机
        mIsShowCamera = getArguments().getBoolean(PrivateContent.EXTRA_SHOW_CAMERA, true);

        initToolbar(view);
        mImageAdapter = new ImageGridAdapter(getActivity(), mIsShowCamera, mCurMode);
        mImageAdapter.setOnPhotoItemCheckedListener(this);
        // 是否显示选择指示器
        mImageAdapter.showSelectIndicator(mCurMode == MODE_MULTI);

        mTimeLineText = (TextView) view.findViewById(R.id.timeline_area);
        // 初始化，先隐藏当前timeline
        mTimeLineText.setVisibility(View.GONE);

        initFolder();
        mGridView = (GridView) view.findViewById(R.id.grid);
        mGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int state) {
                if (state == SCROLL_STATE_IDLE) {
                    // 停止滑动，日期指示器消失
                    mTimeLineText.setVisibility(View.GONE);
                } else if (state == SCROLL_STATE_FLING) {
                    mTimeLineText.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (mTimeLineText.getVisibility() == View.VISIBLE) {
                    int index = firstVisibleItem + 1 == view.getAdapter().getCount() ? view.getAdapter().getCount() - 1 : firstVisibleItem + 1;
                    Image image = (Image) view.getAdapter().getItem(index);
                    if (image != null) {
                        mTimeLineText.setText(TimeUtils.formatPhotoDate(image.mPath));
                    }
                }
            }
        });
        mGridView.setAdapter(mImageAdapter);
        mGridView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            public void onGlobalLayout() {

                final int width = mGridView.getWidth();
                final int height = mGridView.getHeight();
                mGridHeight = height;
                mGridWidth = width;
                mSelectorPhotoFolder.setSize(mGridWidth, mGridHeight);

                final int desireSize = getResources().getDimensionPixelOffset(R.dimen.multi_image_size);
                final int numCount = width / desireSize;
                final int columnSpace = getResources().getDimensionPixelOffset(R.dimen.multi_space_size);
                int columnWidth = (width - columnSpace * (numCount - 1)) / numCount;
                mImageAdapter.setItemSize(columnWidth);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    mGridView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    mGridView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
            }
        });
    }

    private void initFolder() {
        mSelectorPhotoFolder = new SelectorPhotoFolder(getActivity());
        mSelectorPhotoFolder.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
        mSelectorPhotoFolder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                if (position == 0) {
                    getActivity().getSupportLoaderManager().restartLoader(LOADER_ALL, null, mLoaderCallback);
                    mCategoryBtn.setText(R.string.multi_folder_all);
                    mImageAdapter.setShowCamera(mIsShowCamera);
                } else {
                    Adapter adapter = parent.getAdapter();
                    Folder folder = (Folder) adapter.getItem(position);
                    if (null != folder) {
                        mImageAdapter.setDatas(folder.mImages);
                        mCategoryBtn.setText(folder.mName);
                        // 设定默认选择
                        if (mResultList != null && mResultList.size() > 0) {
                            mImageAdapter.setDefaultSelected(mResultList);
                        }
                    }
                    mImageAdapter.setShowCamera(false);
                }

                // 滑动到最初始位置
                mGridView.smoothScrollToPosition(0);
            }
        });
    }

    @Override
    public void onActivityCreated( Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 首次加载所有图片
        //new LoadImageTask().execute();
        getActivity().getSupportLoaderManager().initLoader(LOADER_ALL, null, mLoaderCallback);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 相机拍照完成后，返回图片路径
        if (requestCode == MultiContent.REQUEST_CAMERA) {
            if (resultCode == Activity.RESULT_OK) {
                //小米必须调用，更新系统相机
                MultiImageSelectorUtils.updateMedia(getActivity(), mTmpFile);

                if (mTmpFile != null) {
                    if (mCurMode == MODE_SINGLE_CROP) {
                        //单图拍照
                        MultiImageSelectorUtils.cropPicture(this, Uri.fromFile(mTmpFile), REQUEST_CROP_CAMERA);
                    } else if (mCurMode == MODE_MULTI) {
                        //多图选择
                        //插入当前选择界面的第一个位置，若少于9个，则默认选中，若大于等于9，则不做
                        String name = mTmpFile.getParentFile().getName();
                        Image image = new Image(mTmpFile.getAbsolutePath(), name, mTmpFile.lastModified());
                        for (Folder folder : mResultFolder) {
                            if (name.equals(folder.mName)) {
                                folder.mImages.add(0, image);
                            }
                        }
                        boolean selected = false;
                        if (mMaxCount > mResultList.size()) {
                            selected = true;
                        }
                        mImageAdapter.setNewCamera(image, 0, selected);
                    } else {
                        onCameraShot(mTmpFile);
                    }
                }
            } else {
                if (mTmpFile != null && mTmpFile.exists()) {
                    mTmpFile.delete();
                }
            }
        } else if (requestCode == REQUEST_CROP_SINGLE) {
            if (resultCode == Activity.RESULT_OK) {
                String cropTem = "";
                File cropFile = getCropPicFilePath(data);
                if (cropFile != null) {
                    cropTem = cropFile.getAbsolutePath();
                }
                onSingleImageSelected(cropTem);
            }
        } else if (REQUEST_CROP_CAMERA == requestCode) {
            if (resultCode == Activity.RESULT_OK) {
                File cropFile = getCropPicFilePath(data);
                if (cropFile != null) {
                    onCameraShot(cropFile);
                }
                if (mTmpFile != null && mTmpFile.exists()) {
                    mTmpFile.delete();
                }
            }
        } else if (requestCode == MultiContent.REQUEST_PREVIEW_CODE) {
            //由于启动PreviewActivity的方式是Activity的startActivityForResult，所以在这里处理返回结果
            boolean isexit = data.getBooleanExtra(PrivateContent.EXTRA_EXIT, false);
            ArrayList<String> list = data.getStringArrayListExtra(MultiContent.EXTRA_RESULT);
            if (resultCode == Activity.RESULT_OK) {
                if (isexit) {
                    mResultList.clear();
                    mResultList.addAll(list);
                    mImageAdapter.setDefaultSelected(mResultList);
                } else {
                    Intent intent = new Intent();
                    intent.putStringArrayListExtra(MultiContent.EXTRA_RESULT, list);
                    getActivity().setResult(Activity.RESULT_OK, data);
                    getActivity().finish();
                }
            }
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        Log.d(TAG, "on change");
        if (mSelectorPhotoFolder != null) {
            mSelectorPhotoFolder.hide();
        }

        mGridView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            public void onGlobalLayout() {

                final int height = mGridView.getHeight();
                final int width = mGridView.getWidth();
                mGridHeight = height;
                mGridWidth = width;

                final int desireSize = getResources().getDimensionPixelOffset(R.dimen.multi_image_size);
                Log.d(TAG, "Desire Size = " + desireSize);
                final int numCount = mGridView.getWidth() / desireSize;
                Log.d(TAG, "Grid Size = " + mGridView.getWidth());
                Log.d(TAG, "num count = " + numCount);
                final int columnSpace = getResources().getDimensionPixelOffset(R.dimen.multi_space_size);
                int columnWidth = (mGridView.getWidth() - columnSpace * (numCount - 1)) / numCount;
                mImageAdapter.setItemSize(columnWidth);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    mGridView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    mGridView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
            }
        });

        super.onConfigurationChanged(newConfig);

    }

    /**
     * 选择相机
     */
    private void showCameraAction(Context context) {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断系统相机是否可用
        if (cameraIntent.resolveActivity(context.getPackageManager()) != null) {
            // 设置系统相机拍照后的输出路径
            // 创建临时文件
            mTmpFile = FileUtils.getDicmOrCach(getActivity());
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile));
            startActivityForResult(cameraIntent, MultiContent.REQUEST_CAMERA);
        } else {
            Toast.makeText(getActivity(), R.string.multi_msg_no_camera, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 选择图片操作
     *
     * @param
     */
    private void selectImageFromGrid(ImageGridAdapter.BaseHolder holder, View view) {
        Image image = holder.mData;
        int mode = mCurMode;
        if (image == null) {
            return;
        }
        // 多选模式
        if (mode == MODE_MULTI) {
            int position = holder.mPosition;
            if (view.getId() == R.id.layout_item_parent) {
                List<Image> curFloderImageList = mImageAdapter.getData();
                ArrayList<String> imageList = new ArrayList<String>();
                if (curFloderImageList != null) {
                    for (Image data : curFloderImageList) {
                        imageList.add(data.mPath);
                    }
                }
                if (mImageAdapter.isShowCamera()) {
                    position = position - 1;
                }
//                MultiImagePreviewActivity.previewPictures(this, imageList, 0);
                MultiImageSelectorUtils.previewAndChoose(this, imageList, mResultList, mMaxCount, position);
//                MultiImagePreviewActivity.previewAndSave(this, imageList, mPosition, null);
            } else {
                if (mResultList.contains(image.mPath)) {
                    mResultList.remove(image.mPath);
                    onImageUnselected(image.mPath);
                } else {
                    // 判断选择数量问题
                    if (mMaxCount == mResultList.size()) {
                        Toast.makeText(getActivity(), R.string.multi_msg_amount_limit, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    mResultList.add(image.mPath);
                    onImageSelected(image.mPath);
                }
                mImageAdapter.select(holder);
            }
        } else if (mode == MODE_SINGLE) {
            // 单选模式
            onSingleImageSelected(image.mPath);
        } else if (mode == MODE_SINGLE_CROP) {
            MultiImageSelectorUtils.cropPicture(this, Uri.fromFile(new File(image.mPath)), REQUEST_CROP_SINGLE);
        }
    }

    /***
     * 裁剪图片
     *
     * @param activity    Activity
     * @param uri         图片的Uri
     * @param requestCode the code
     */
    public void cropPicture(Activity activity, Uri uri, int requestCode) {
        Intent innerIntent = new Intent("com.android.camera.action.CROP");
        innerIntent.setDataAndType(uri, "image/*");
        innerIntent.putExtra("crop", "true");
        // 才能出剪辑的小方框，不然没有剪辑功能，只能选取图片
        innerIntent.putExtra("aspectX", 1);
        // 放大缩小比例的X
        innerIntent.putExtra("aspectY", 1);
        final int outputX = 320;
        // 放大缩小比例的X   这里的比例为：   1:1
        innerIntent.putExtra("outputX", outputX);
        //这个是限制输出图片大小
        innerIntent.putExtra("outputY", outputX);
        innerIntent.putExtra("return-mData", true);
        innerIntent.putExtra("scale", true);
        startActivityForResult(innerIntent, requestCode);
    }

    /**
     * 获取剪切的图片，并保存为文件
     *
     * @param intent
     * @return
     */
    private File getCropPicFilePath(Intent intent){
        Bitmap bitmap = intent.getParcelableExtra("data");
//        String fileName = String.valueOf(System.currentTimeMillis()) + ".jpg";
        File tempFile = FileUtils.getDicmOrCach(getActivity());//new File(, fileName);

        // 图像保存到文件中
        FileOutputStream foutput = null;
        try {
            foutput = new FileOutputStream(tempFile);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, foutput)) {
                Log.e("Utils", "缓存文件位置：" + tempFile.getAbsolutePath());
            }
            return tempFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private LoaderManager.LoaderCallbacks<Cursor> mLoaderCallback = new LoaderManager.LoaderCallbacks<Cursor>() {

        private final String[] mImageProjection = {
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Media._ID};

        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            if (id == LOADER_ALL) {
                CursorLoader cursorLoader = new CursorLoader(getActivity(),
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, mImageProjection,
                        null, null, mImageProjection[2] + " DESC");
                return cursorLoader;
            } else if (id == LOADER_CATEGORY) {
                CursorLoader cursorLoader = new CursorLoader(getActivity(),
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, mImageProjection,
                        mImageProjection[0] + " like '%" + args.getString("mPath") + "%'", null, mImageProjection[2] + " DESC");
                return cursorLoader;
            }

            return null;
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            if (data != null) {
                List<Image> imageAll = new ArrayList<>();
                int count = data.getCount();
                if (count > 0) {
                    data.moveToFirst();
                    do {
                        String path = data.getString(data.getColumnIndexOrThrow(mImageProjection[0]));
                        String name = data.getString(data.getColumnIndexOrThrow(mImageProjection[1]));
                        long dateTime = data.getLong(data.getColumnIndexOrThrow(mImageProjection[2]));
                        Image image = new Image(path, name, dateTime);
                        if (path.endsWith(".gif")) {
                            continue;
                        }
                        imageAll.add(image);
                        if (!mHasFolderGened) {
                            // 获取文件夹名称
                            File imageFile = new File(path);
                            File folderFile = imageFile.getParentFile();
                            Folder folder = new Folder();
                            folder.mName = folderFile.getName();
                            folder.mPath = folderFile.getAbsolutePath();
                            folder.mCover = image;
                            if (!mResultFolder.contains(folder)) {
                                List<Image> imageList = new ArrayList<>();
                                imageList.add(image);
                                folder.mImages = imageList;
                                mResultFolder.add(folder);
                            } else {
                                // 更新
                                Folder f = mResultFolder.get(mResultFolder.indexOf(folder));
                                f.mImages.add(image);
                            }
                        }

                    } while (data.moveToNext());

                    mImageAdapter.setDatas(imageAll);

                    // 设定默认选择
                    if (mResultList != null && mResultList.size() > 0) {
                        mImageAdapter.setDefaultSelected(mResultList);
                    }

//                    mFolderAdapter.setDatas(mResultFolder);
                    mSelectorPhotoFolder.update(mResultFolder);
                    mHasFolderGened = true;

                }
            }
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {

        }
    };


    @Override
    public void onViewClick(ImageGridAdapter.BaseHolder holde, View convertView) {
        int position = holde.mPosition;
        if (mImageAdapter.isShowCamera() && position == 0) {
            // 如果显示照相机，则第一个Grid显示为照相机，处理特殊逻辑
//            showCameraAction(getActivity().getApplication());
            mTmpFile = MultiImageSelectorUtils.tackPicture(this);
        } else {
            // 正常操作
            selectImageFromGrid(holde, convertView);
        }
    }

    private void onSingleImageSelected(String path) {
        Intent data = new Intent();
        mResultList.add(path);
        data.putStringArrayListExtra(MultiContent.EXTRA_RESULT, mResultList);
        getActivity().setResult(Activity.RESULT_OK, data);
        getActivity().finish();
    }

    private void onImageSelected(String path) {
        if (!mResultList.contains(path)) {
            mResultList.add(path);
        }
        // 有图片之后，改变按钮状态
        if (mResultList.size() > 0) {
            refrashSubmit();
        }
    }

    private void onImageUnselected(String path) {
        if (mResultList.contains(path)) {
            mResultList.remove(path);
        }
        refrashSubmit();
    }

    //更新系统相册
//    private void updateMedia(File imageFile) {
//        getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageFile)));
//        // 刷新系统相册
//    }

    private void onCameraShot(File imageFile) {
        if (imageFile != null) {
            //适配
            Intent data = new Intent();
            mResultList.add(imageFile.getAbsolutePath());
            data.putStringArrayListExtra(MultiContent.EXTRA_RESULT, mResultList);
            getActivity().setResult(Activity.RESULT_OK, data);
            getActivity().finish();
        }
    }
}
